import { ErrorInfo, PureComponent, ReactNode } from 'react';
import { Button, Result, Typography } from 'antd';

const { Paragraph, Text } = Typography;

interface IProps {
  children: ReactNode;
}

interface StateProps {
  hasError: boolean;
  error: null | Error;
}

class ErrorBoundary extends PureComponent<IProps, StateProps> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      hasError: false,
      error: null,
    };
  }

  static getDerivedStateFromError(error: Error) {
    return {
      hasError: true,
      error,
    };
  }
  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.log(error, errorInfo);
  }

  render(): ReactNode {
    return (
      <>
        {this.state.hasError ? (
          <Result
            status="error"
            title="遇到了不可避免的错误"
            subTitle="请在重新提交之前检查并修改以下信息。"
            extra={[
              <Button type="primary" key="console" onClick={() => location.reload()}>
                刷新
              </Button>,
              <Button key="buy">提交错误(待上线)</Button>,
            ]}
          >
            <div className="desc">
              <Paragraph>
                <Text
                  strong
                  style={{
                    fontSize: 16,
                  }}
                >
                  {this.state.error?.message}
                </Text>
              </Paragraph>
              <Paragraph>
                <Text>{this.state.error?.stack}</Text>
              </Paragraph>
            </div>
          </Result>
        ) : (
          this.props.children
        )}
      </>
    );
  }
}

export default ErrorBoundary;
